package com.example.charactivity

import android.app.usage.UsageStats
import android.util.Log
import com.example.charactivity.ChartDaily.DayChartViewModel

import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*

data class UseTime(var name:String,var timeMillis:Long)
class UsageStatics {
    companion object instance {
        fun getDayStart(value:Int,upDay: Int =0): Long {// the function return the day's start millis
            val nowtime = Calendar.getInstance()
            var cal = Calendar.getInstance()
            cal.add(Calendar.DATE,upDay) // 往后加一天
            cal.set(Calendar.HOUR_OF_DAY, value)
            cal.set(Calendar.SECOND, 0)
            cal.set(Calendar.MINUTE, 0)
            cal.set(Calendar.MILLISECOND, 0)
            Log.d("time", nowtime.timeInMillis.toString())
            //1621425474102
            Log.d("time", cal.timeInMillis.toString())
            //  val millis=-cal.timeInMillis =1621382400000
            // return Timestamp(cal.timeInMillis)
            return cal.timeInMillis  // 返回的是修改后的毫秒

        }
    }



    fun printState(usageStats: UsageStats?) {
         var arrayData= arrayOfNulls<UseTime>(5)
         var i=0
        val format: DateFormat = SimpleDateFormat("yyyy.MM.dd_HH:mm:ss", Locale.getDefault())

        val packageName = usageStats!!
            .packageName

        val beginningTime: String =
            format.format(Date(usageStats.firstTimeStamp))  // 在查询的时间段内，上次使用的使劲按
        val endTime: String = format.format(Date(usageStats.lastTimeStamp))
        val lastUsedTime: String = format.format(Date(usageStats.lastTimeUsed)) //上次使用时间

        val usedTime = formatDuring(usageStats.totalTimeInForeground)

        val foregroundTime = usageStats.totalTimeInForeground / 1000 //前台总共运行的时间，单位是秒

        var appLaunchCount = 0 //应用被拉起启动次数

        var launchCount = 0 //应用前台启动次数(包括自己启动其他activity)

        try {
            appLaunchCount =
                usageStats::class.java.getDeclaredMethod("getAppLaunchCount")
                    .invoke(usageStats) as Int
            launchCount = usageStats.javaClass.getDeclaredField("mLaunchCount").getInt(usageStats)
        } catch (e: Exception) {
            e.printStackTrace()
        }



        Log.i(
            "bqt",
            "| $packageName | $beginningTime | $endTime | $lastUsedTime | $usedTime | $appLaunchCount | $launchCount |"
        )
         arrayData[i++]=UseTime(packageName,foregroundTime)  //得到在一天内使用最多的5个app，！
    }

    fun formatDuring(mss: Long): String? {
        val days = mss / (1000 * 60 * 60 * 24)
        val hours = mss % (1000 * 60 * 60 * 24) / (1000 * 60 * 60)
        val minutes = mss % (1000 * 60 * 60) / (1000 * 60)
        val seconds = mss % (1000 * 60) / 1000
        return (days.toString() + " days " + hours + " hours " + minutes + " minutes "
                + seconds + " seconds ")
    }


}